﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage.Streams;

#if NETFX_CORE
using Windows.Security.Cryptography;
using System.Runtime.InteropServices.WindowsRuntime;
#else
using System.Security.Cryptography;
#endif

namespace Windows.Storage
{
    public static class FileHelper
    {
        public static async Task<IStorageFile> ToFile(this string path)
        {
            return await StorageFile.GetFileFromApplicationUriAsync(new Uri(path));
        }

        public static async Task<string> ReadBufferAsync(this IBuffer utf8)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                IOutputStream outputStream = stream.AsOutputStream();
                await outputStream.WriteAsync(utf8);

                stream.Seek(0, SeekOrigin.Begin);
                using (StreamReader sr = new StreamReader(stream))
                {
                    return sr.ReadToEnd();
                }
            }
        }

        private static readonly StorageFolder local = ApplicationData.Current.LocalFolder;
        public static async Task CopyToLocal(string path)
        {
            IStorageFile source = await string.Format("ms-appx:///Data/{0}", path).ToFile();
            await source.CopyAsync(local, path, NameCollisionOption.ReplaceExisting);
        }

#if NETFX_CORE
        private static readonly StorageFolder temp = ApplicationData.Current.TemporaryFolder;
        public static async Task CopyToTemp(string path)
        {
            IStorageFile source = await string.Format("ms-appx:///Data/{0}", path).ToFile();
            await source.CopyAsync(temp, path, NameCollisionOption.ReplaceExisting);
        }
#endif
        private static readonly string[] letters = "A,Á,B,C,Č,D,Ď,E,É,Ě,F,G,H,Ch,I,Í,J,K,L,M,N,Ň,O,Ó,P,Q,R,Ř,S,Š,T,Ť,U,Ú,Ů,V,W,X,Y,Ý,Z,Ž".Split(new [] {','});
        private static readonly Random random = new Random();

        public static string RandomString()
        {
            return string.Concat(Enumerable.Range(1, 40).Select(i => letters[random.Next(letters.Length)]));
        }

        public static List<string> RandomMultilineList()
        {
            return Enumerable.Range(1, 10).Select(i => RandomString()).ToList();
        }

        public static string RandomMultilineText()
        {
            return string.Join(Environment.NewLine, RandomMultilineList());
        }

        public static byte[] RandomBytes(uint length)
        {
            byte[] bytes = new byte[length];
#if NETFX_CORE
            IBuffer randomBuffer = CryptographicBuffer.GenerateRandom(length);
            randomBuffer.CopyTo(bytes);
#else
            RandomNumberGenerator rng = new RNGCryptoServiceProvider();
            rng.GetBytes(bytes);
#endif
            return bytes;
        }
    }
}